<template>
    <div class="wrapper">
        <h1>watch</h1>
        <h2>一、基本类型</h2>
        <h2>当前 求和：{{ sum }}</h2>
        <h2>当前 Watch：{{ watchSum }}</h2>
        <button @click="changeSum"> +1 </button>
        <h2>二、ref对象</h2>
        <h2>姓名：{{ person.name }}</h2>
        <h2>age:{{ person.age }}</h2>
        <button @click="changeName">修改姓名 </button>
        <h2>三、reactive对象</h2>
        <h2>姓名：{{ person1.name }}</h2>
        <h2>age:{{ person1.age }}</h2>
        <button @click="changeName1">修改人 </button>
        <h2>四、监听对象属性</h2>
        <h2>姓名：{{ person2.name }}</h2>
        <h2>age:{{ person2.age }}</h2>
        <h2>car:{{ person2.car.name }}</h2>
        <button @click="changeCar">换车 </button>
        <h2>四、监听对象属性-多个</h2>
        <h2>姓名：{{ person3.name }}</h2>
        <h2>age:{{ person3.age }}</h2>
        <h2>car:{{ person3.car.name }}</h2>
        <button @click="changeName5">修改名字 </button>
        <button @click="changeAge5">修改年龄 </button>
        <button @click="changeCar5">换车 </button>
    </div>
</template>

<script lang="ts" setup name="Watch">

import { ref, reactive, watch } from 'vue'

/**
 * 一、watch基本类型
 */
let sum = ref(0)
let watchSum = ref(0)
function changeSum() {
    sum.value++
}

const stopWatch1 = watch(sum, (newV, oldV) => {
    console.log(oldV, '->', newV)
    watchSum.value = newV
    if (newV > 10) {
        watchSum.value = 999
        stopWatch1()
    }
})

/**
 * 二、watch对象类型-ref
 */
let person = ref({
    name: '张三',
    age: 18
})

function changeName() {
    person.value.name += '~'
}

// deep:深度监视 immediate:立即执行
watch(person, (newV, oldV) => {
    console.log('Watch.vue {immediate: true},立即执行', oldV, ' -> ', newV)
}, { deep: true, immediate: true })

/**
 * 三、watch对象类型-reactive
 */
let person1 = reactive({
    name: '张三',
    age: 18
})

function changeName1() {
    Object.assign(person1, { name: "李四", age: 999 })
}
// reactive 默认deep：true
watch(person1, (newV, oldV) => {
    console.log(oldV, '->', newV)
})

/**
 * 四、watch对象类型的某个属性
 */
let person2 = ref({
    name: "赵武",
    age: 20,
    car: {
        name: '奔驰'
    }
})
function changeCar() {
    person2.value.car.name += '~'
}

// 需要用函数返回
watch(() => person2.value.car.name, (newV, oldV) => {
    console.log(oldV, '->', newV)
})

/**
 * 五、
 */
let person3 = reactive({
    name: "老刘",
    age: 20,
    car: {
        name: '宝马'
    }
})
function changeName5() {
    person3.name += "~"
}
function changeAge5() {
    person3.age++
}
function changeCar5() {
    person3.car.name += '~'
}

// 数组形式，value也为数组
watch([() => person3.age, () => person3.car.name], (newV, oldV) => {
    console.log(oldV, '->', newV)
})
</script>

<style scoped>
.wrapper {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
    margin: 20px
}

button {
    margin: 0 5px;
}
</style>